import { useEffect, useState } from 'react';
import { message } from 'antd';
import { LoadingOutlined, RightOutlined } from '@ant-design/icons';
import Modals from '@/components/modals/Modals';
import { useKnowledgeStore } from '@/store/knowledge';
import { SvgIcon } from '@/components/icon';
import { DislikeQuestionAnnotationType, FaqDataset } from '@/types/know/know';
import useModal from '@/hooks/use-modal/useModal';
import knowService from '@/api/services/knowService';
import { CustomDatePicker, TextArea } from '@/components/eai-design';
import dayjs, { Dayjs } from 'dayjs';
import DrawerView from '../components/DrawerView';
import Markdown from '@/components/markdown';
import FaqListModal from '../components/faqListModal';
import { useParams } from '@/router/hooks';

interface Props {
  open: boolean;
  onCancel: () => void;
  onOk: () => void;
  onOverlook?: () => void;
}

export default function DislikeDisposeModal({ open, onCancel, onOk, onOverlook }: Props) {
  const { appId = '' } = useParams() as { appId: string };
  const [answer, setAnswer] = useState('');
  const [validDate, setValidDate] = useState<Dayjs | null>(null);
  const { dislikeItem } = useKnowledgeStore();
  const modal = useModal('editQuestion', 'faqOpen', 'test');
  const [showAIAnswer, setShowAIAnswer] = useState(true);
  const [faqDataset, setFaqDataset] = useState<FaqDataset>({} as FaqDataset);
  const [keyQuestionText, setKeyQuestionText] = useState('');
  const [keyQuestionQaId, setKeyQuestionQaId] = useState('');
  const [aiLoading, setAiLoading] = useState(false);
  useEffect(() => {
    setFaqDataset({} as FaqDataset);
    setValidDate(null);
    setAnswer('');
    setShowAIAnswer(true);
  }, [dislikeItem]);

  // 有效期设置
  const handleDateChange = (date: Dayjs | null) => {
    if (!date) {
      setValidDate(null);
      return;
    }
    const endOfDay = date.set('hour', 23).set('minute', 59).set('second', 59);
    setValidDate(endOfDay);
  };
  //AI润色
  const handerAICreate = async () => {
    if (aiLoading || answer.length < 10) {
      message.warning('请输入至少10个字符');
      return;
    }
    try {
      setAiLoading(true);
      let res;
      if (showAIAnswer) {
        //AI润色
        res = await knowService.dislikeAICreat({
          question: dislikeItem.keyQuestionText,
          appId: appId,
          keyQuestionQaId: dislikeItem.qaId || '',
          answer: answer,
        });
        setShowAIAnswer(false);
        setAnswer(res.aiembellish);
        message.success('AI润色成功');
      } else {
        //撤回润色
        res = await knowService.AIback({
          question: dislikeItem.keyQuestionText,
          keyQuestionQaId: dislikeItem.qaId || '',
          appId: appId,
        });
        setAnswer(res);
        setShowAIAnswer(true);
        message.success('撤回润色成功');
      }
    } catch (error) {
      message.error('AI润色失败');
    } finally {
      setAiLoading(false);
    }
  };

  //写一个方法用来判断是否可以提交
  const isOk = () => {
    if (faqDataset.datasetId != undefined && faqDataset.datasetId != '' && answer.length != 0) {
      return true;
    }
    return false;
  };
  //提交
  const handleSubmit = async () => {
    if (faqDataset.datasetId == undefined || faqDataset.datasetId == '') {
      message.warning('请填写知识库');
      return;
    }
    if (answer.length == 0) {
      message.warning('请输入标准答案');
      return;
    }
    //收集参数
    const params = {
      id: dislikeItem._id,
      appId: appId,
      qaId: dislikeItem.qaId || '',
      question: dislikeItem.keyQuestionText,
      answer: answer,
      datasetId: faqDataset.datasetId,
      experiodTime: validDate ? validDate.format('YYYY-MM-DD HH:mm:ss') : '',
    };
    try {
      await knowService.updateDislikeQuestionAnnotation(params as DislikeQuestionAnnotationType);
      onOk();
    } catch (error) {
      message.error(error as string);
    }
  };

  return (
    <>
      <Modals
        open={open}
        onCancel={onCancel}
        title="用户点踩问题"
        width={1200}
        modelContentClassName="!my-3 !p-0 !mx-4 hide-scrollbar"
        footer={
          <div className="flex justify-end gap-2 border-t border-t-line-2 p-4">
            <div
              className={`ml-4 flex h-[32px] w-[68px] cursor-pointer items-center justify-center rounded-md border 
                   !border-@brand-color !text-@brand-color
              `}
              onClick={onOverlook}
            >
              忽略
            </div>
            <div
              className={`ml-4 flex h-[32px] w-[68px]  items-center justify-center rounded-md border text-white 
                   ${
                     isOk()
                       ? 'cursor-pointer !border-@brand-color !bg-@brand-color'
                       : '!border-@brand-disabled cursor-not-allowed !bg-@brand-color-disabled'
                   }
              `}
              style={
                isOk() ? { background: 'linear-gradient(90deg, #1B6DFA 0%, #00D0FE 181.25%)' } : {}
              }
              onClick={handleSubmit}
            >
              完成
            </div>
          </div>
        }
      >
        <div className="flex">
          {/* 右侧标准答案编辑 */}
          <div className="flex flex-1 flex-col">
            <div className="mb-2 flex h-[40px] items-center rounded-lg border border-geekblue-1 bg-geekblue-1 text-sm leading-[40px] text-text-5">
              <SvgIcon size={20} className="mx-2 cursor-pointer" icon="report-is-outline" />
              为点踩问题添加合适答案，提高用户试用满意度。
            </div>
            <div className="flex items-center gap-4">
              <div className=" h-full w-1/2 rounded-md bg-bg-3 px-4 py-2  text-text-3">
                <div className="mb-2 flex items-center">
                  <span className="text-base font-bold text-text-5">用户问题：</span>
                </div>
                <div className="mb-2 flex items-center text-base font-bold text-@brand-color">
                  {dislikeItem.keyQuestionText}
                </div>
                <div className="mb-2 text-base font-bold text-text-5">AI当前回答：</div>
                <div className="hide-scrollbar h-[310px] overflow-y-auto">
                  <Markdown source={dislikeItem.keyQuestionAnswer} />
                </div>
              </div>
              <div className="w-1/2 rounded-md bg-bg-3 px-4 py-2  text-text-3">
                <div className="flex items-center justify-between">
                  <div>
                    <div className="mb-2 flex items-center">
                      <span className="text-base font-bold text-text-5">添加标准答案</span>
                    </div>
                    <div className="mb-2 text-sm text-text-3">
                      输入标准答案，用户后续询问相关问题从标准答案形式回复用户
                    </div>
                  </div>
                  <div className="flex items-center">
                    <div
                      className={`
                          flex items-center rounded-md border border-line-2 px-2 py-1 text-sm font-semibold
                         ${
                           aiLoading || answer.length < 10
                             ? 'cursor-not-allowed '
                             : 'cursor-pointer '
                         }
                      `}
                      style={
                        answer.length < 10
                          ? {
                              background:
                                'linear-gradient(90deg, rgba(146, 83, 244, 0.10) -11.61%, rgba(39, 119, 255, 0.10) 52.92%, rgba(0, 208, 254, 0.10) 116.22%), #FFF',
                              opacity: 0.5,
                              color: 'var(--disabled, #BADDFF)',
                            }
                          : {
                              background:
                                'linear-gradient(90deg, rgba(146, 83, 244, 0.10) -11.61%, rgba(39, 119, 255, 0.10) 52.92%, rgba(0, 208, 254, 0.10) 116.22%), #FFF',
                              opacity: 1,
                              color: '#1D2129',
                            }
                      }
                      onClick={() => {
                        if (!aiLoading && answer.length >= 10) handerAICreate();
                      }}
                    >
                      {aiLoading ? (
                        <LoadingOutlined spin />
                      ) : (
                        <SvgIcon size={16} icon="report-is-runse" />
                      )}
                      <span
                        style={
                          answer.length < 10
                            ? undefined
                            : {
                                backgroundImage:
                                  'linear-gradient(90deg, rgba(146, 83, 244, 1) -11.61%, rgba(39, 119, 255, 1) 52.92%, rgba(0, 208, 254, 1) 116.22%)',
                                WebkitBackgroundClip: 'text',
                                backgroundClip: 'text',
                                WebkitTextFillColor: 'transparent',
                                color: 'transparent',
                              }
                        }
                      >
                        {showAIAnswer ? 'AI润色' : '撤回润色'}
                      </span>
                    </div>
                    {/* <Button
                    type="default"
                    className="ml-2 !bg-[#F7F8F8]"
                    onClick={() => {
                      modal.test.open();
                      setKeyQuestionText(dislikeItem.keyQuestionText);
                      setKeyQuestionQaId(dislikeItem.qaId || '');
                    }}
                  >
                    测试
                  </Button> */}
                  </div>
                </div>
                <TextArea
                  placeholder="请输入标准答案"
                  autoSize={{ minRows: 15, maxRows: 15 }}
                  value={answer}
                  onChange={(e) => setAnswer(e.target.value)}
                  className="border border-text-2 "
                />
                <div className="mt-2 flex items-center gap-2 text-sm text-text-4">
                  存放至
                  <div
                    className="flex w-[170px] cursor-pointer items-center justify-between rounded-lg border border-line-2 bg-white px-2 py-1 text-text-4"
                    onClick={() => {
                      modal.faqOpen.open();
                    }}
                  >
                    <span>
                      <span className={`${faqDataset.datasetId ? 'text-text-4' : 'text-text-2'}`}>
                        {faqDataset.datasetId ? faqDataset?.datasetName : '请选择存放位置'}
                      </span>
                    </span>
                    <RightOutlined />
                  </div>
                  <span className="  ">
                    答案有效期：
                    {/* <span className="mr-2">{validDate ? validDate.format('YYYY-MM-DD') : '无'}</span> */}
                    <CustomDatePicker
                      placeholder="无有效期"
                      value={validDate as Dayjs}
                      format="YYYY-MM-DD HH:mm:ss"
                      onChange={handleDateChange}
                      disabledDate={(current) => {
                        return current && current < dayjs().startOf('day');
                      }}
                    />
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </Modals>

      <FaqListModal
        open={modal.faqOpen.isOpen}
        onOk={(item) => {
          setFaqDataset(item);
          modal.faqOpen.close();
        }}
        onCancel={() => modal.faqOpen.close()}
        appId={appId}
      />
      <DrawerView
        open={modal.test.isOpen}
        onClose={() => {
          modal.test.close();
        }}
        keyQuestionText={keyQuestionText}
        keyQuestionQaId={keyQuestionQaId}
      />
    </>
  );
}
